<template>
  <div>
    <el-form
      :model="form"
      :rules="rules"
      ref="basicInfo"
      label-width="160px"
      class="demo-ruleForm"
    >
      <el-row type="flex" justify="center" :gutter="0">
        <el-col :span="12">
          <el-form-item label="填报单位：" prop="reportInOrgName">
            <!-- <el-input v-model="form.reportInOrgName" disabled></el-input> -->
            <el-select
              v-model="form.reportInOrgName"
              placeholder="请选择填报单位"
              @change="changeReportInOrgId"
              style="width: 100%"
            >
              <el-option
                v-for="item in reportOptions"
                :key="item.orgId"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" :offset="4">
          <el-form-item label="部门：" prop="departName">
            <el-select
              ref="selectTree"
              v-model="form.departName"
              placeholder="请选择部门"
              popper-class="popperTreeSelect"
              style="width: 100%"
            >
              <el-option label="" value="">
                <el-tree
                  :data="departOptions"
                  :props="{ children: 'child', label: 'abbrName' }"
                  @node-click="handleNodeClick"
                >
                  <span
                    :class="{
                      'depart-tree-node': form.departName === node.data.abbrName
                    }"
                    slot-scope="{ node }"
                  >
                    {{ node.data.abbrName }}
                  </span>
                </el-tree>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row type="flex" justify="center" :gutter="0">
        <el-col :span="12">
          <el-form-item label="业务类型：">
            <el-input v-model="form.businessTypeName" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="4" class="relative">
          <el-form-item label="项目名称：" prop="projectName">
            <el-input v-model="form.projectName" disabled />
            <el-button
              plain
              type="single-number"
              size="mini"
              class="chereay"
              @click="handleShowProjectNameDialog"
              >选择</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>

      <el-row type="flex" justify="center" :gutter="0">
        <el-col :span="12" class="relative">
          <el-form-item label="核算组织：" prop="accountingOrgan">
            <el-input
              v-model="form.accountingOrgan"
              disabled
              placeholder="请选择核算组织"
            />
            <el-button
              plain
              type="single-number"
              size="mini"
              class="chereay"
              @click="handleShowAccountingOrganDialog"
              >选择
            </el-button>
          </el-form-item>
        </el-col>

        <el-col :span="12" :offset="4">
          <el-form-item label="本位币：" prop="standardMoney">
            <el-select
              v-model="form.standardMoney"
              placeholder="请选择本位币"
              style="width: 100%"
            >
              <el-option
                v-for="item in reportOptions"
                :key="item.orgId"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row type="flex" justify="center" :gutter="0">
        <el-col :span="12">
          <el-form-item label="发票单名称：" prop="invoiceName">
            <el-input
              v-model="form.invoiceName"
              placeholder="请输入发票单名称"
              maxlength="300"
              show-word-limit
              @blur="handleTrim('invoiceName')"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12" :offset="4">
          <el-form-item label="发票单编号：" prop="invoiceCode">
            <el-input
              type="text"
              v-model="form.invoiceCode"
              show-word-limit
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row type="flex" justify="center" :gutter="0">
        <el-col :span="12" class="relative">
          <el-form-item label="结算单编号：" prop="settlementCode">
            <el-input v-model="form.settlementCode" disabled />
            <el-button
              plain
              type="single-number"
              size="mini"
              class="chereay"
              @click="showDialog"
              >选择
            </el-button>
          </el-form-item>
        </el-col>

        <el-col :span="12" :offset="4">
          <el-form-item label="结算单名称：" prop="settlementName">
            <el-input
              v-model="form.settlementName"
              placeholder="请输入结算单名称"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row type="flex" justify="center" :gutter="0">
        <el-col :span="12">
          <el-form-item label="供应商：" prop="partyBName">
            <el-input
              v-model="form.partyBName"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="4"> </el-col>
      </el-row>

      <el-row type="flex" justify="center" :gutter="0">
        <el-col :span="12">
          <el-form-item label="合同编号：" prop="contractCode">
            <el-input v-model="form.contractCode" disabled />
          </el-form-item>
        </el-col>

        <el-col :span="12" :offset="4">
          <el-form-item label="合同名称：" prop="contractName">
            <el-input v-model="form.contractName" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row type="flex" justify="center" :gutter="0">
        <el-col :span="12">
          <el-form-item label="分类名称：" prop="categoryName">
            <el-input v-model="form.categoryName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="4">
          <el-form-item label="币种：" prop="currency">
            <el-input v-model="form.currency" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row type="flex" justify="center" :gutter="0">
        <el-col :span="12">
          <el-form-item label="结算金额：" prop="settlementAmount">
            <el-input v-model="form.settlementAmount" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="4">
          <el-form-item label="已收票金额：" prop="totalInvoiceAmount">
            <el-input v-model="form.totalInvoiceAmount" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row type="flex" justify="center" :gutter="0">
        <el-col :span="12">
          <el-form-item label="本次收票金额：" prop="currentInvoiceAmount">
            <el-input v-model="form.currentInvoiceAmount" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="4">
          <el-form-item label="发票张数：" prop="invoiceNum">
            <el-input v-model="form.invoiceNum" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row type="flex" justify="center" :gutter="0">
        <el-col :span="12">
          <el-form-item label="编制人：" prop="compileUser">
            <el-input v-model="form.compileUser" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="4">
          <el-form-item label="编制日期：" prop="compileDate">
            <el-date-picker
              v-model="form.compileDate"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
              disabled
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row
        type="flex"
        justify="flex-start"
        :gutter="0"
        style="margin-top: -10px"
      >
        <el-col :span="24">
          <el-form-item label="备注：" prop="remark">
            <el-input
              resize="both"
              type="textarea"
              :rows="5"
              style="margin-top: 10px; border-radius: 4px"
              placeholder="请输入备注说明"
              maxlength="1000"
              show-word-limit
              v-model="form.remark"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- <chooseSettlement ref="chooseSettlement" /> -->
    <codeNumber
      style="display: inline-block; height: 20px"
      ref="codeNumber"
      :reportInOrgId="this.form.reportInOrgId"
      :settlementCode="this.form.settlementCode"
      @inventoryConfirm="codeNumberInventoryConfirm"
    ></codeNumber>
    <!-- 项目名称 -->
    <chooseSupplier
      ref="projectNameBakVisibleDialog"
      :supplierData="projectObj"
      @selectPartyB="selectProjectName"
    />
    <!-- 核算组织 -->
    <chooseSupplier
      ref="accountingOrgan"
      :supplierData="accountingOrganObj"
      @selectPartyB="selectAccountingOrganName"
    />
  </div>
</template>

<script>
import { getSettlementById } from "../../../settlement-management/settlement-maintenance-approval/api/settlement-approval";
import codeNumber from "../components/codeNumber.vue";
import { getUserInfo, getReportInOrgData, qryUnderOrg, listAccountingUnitByBO } from "@/basa/api";
import { addUrlPerFix } from "@/basa/utils";
import BigNumber from "bignumber.js";
import {qryProjectDataAll} from '../api';
import jsList from '../js';
import publicComponent from "@/basa/components/public";
import { mapGetters } from "vuex";

export default {
  name: "basicInfo",
  components: {
    codeNumber,
    chooseSupplier: publicComponent.singleSupplier,
  },
  props: {
    form: Object
  },
  data() {
    return {
      jsList,
      currentId: "",
      reportInOrgObj: {
        title: "填报单位查询",
        tableData: [],
        recordsTotal: 0,
        formDate: {
          mainType: "A",
          orgid: "",
          pageNo: 1,
          pageSize: 10
        }
      },
      reportOptions: [], // 填报单位
      rules: {
        invoiceName: [
          {
            required: true,
            message: "请输入发票单名称",
            trigger: "blur"
          }
        ],
        partyBName: [
          {
            required: true,
            message: "请输入供应商",
            trigger: "change"
          }
        ],
        settlementCode: [
          {
            required: true,
            message: "请选择结算单编号",
            trigger: "change"
          }
        ],
        accountingOrgan: [
          {
            required: true,
            message: "请选择核算组织",
            trigger: "blur"
          }
        ],
        projectName: [
          {
            required: true,
            message: "请选择项目名称",
            trigger: "blur"
          }
        ],
        standardMoney: [
          {
            required: true,
            message: "请选择本位币",
            trigger: "blur"
          }
        ]
      },
      departOptions:[],
      projectObj: {
        title: "项目名称查询",
        tableHeadOptions: jsList.projectTableHead,
        tableData: [],
        recordsTotal: 0,
        formDate: {
          fillOrg: "",
          pageNo: 1,
          pageSize: 10
        }
      },
      accountingOrganObj: {
        title: "核算组织查询",
        tableHeadOptions: jsList.accountingOrganTableHead,
        tableData: [],
        recordsTotal: 0,
        formDate: {
          pageNo: 1,
          pageSize: 10
        }
      },
    };
  },
  created() {
    //   发票张数
    this.$bus.$on("tableLength", message => {
      this.$set(this.form, "invoiceNum", message);
      if (message == 0) {
        this.$set(this.form, "currentInvoiceAmount", Number("0").toFixed(2));
      } //发票张数为0清空本次收票金额
    });
    // 发票清单
    this.$bus.$on("invoiceTableBill", val => {
      if (val) {
        // console.log(val, "val");
        let names = ["amountExcludeTax", "tax", "amount"];
        names.forEach((item, index) => {
          this.form[item] = val[index];
        });
        // 本次收票金额
        this.form.currentInvoiceAmount = val[2];
      }
    });
    // 本次收票金额
    // this.$bus.$on("priceTaxTotalSum", message => {
    //     this.$set(this.form, "currentInvoiceAmount", Number(message).toFixed(2));
    // });
  },
  activated() {
    this.$refs.basicInfo.resetFields(); //每次进入清空表单
    this.getUserInfo();
  },
  watch: {
    "form.reportInOrgName": {
      handler:function(n) {
        if (n) {
          const tempObj = this.reportOptions.find(e => e.name === n);
          if (tempObj) {
            console.log(tempObj)
            this.form.reportInOrgId = tempObj.orgId;
            this.form.reportInOrgName = tempObj.name;
            this.getDepartData(this.form.reportInOrgId);
          }
        }
      },
      immediate: true,
      deep: true
    }
  },
  computed: {
    ...mapGetters([
      "getSelectProjectNameStrategy" // 项目名称操作
    ])
  },
  methods: {
    getUserInfo() {
      getUserInfo(
        addUrlPerFix(process.env.VUE_APP_BASEP_URL) + "/apis/basap/getUserInfo",
        {}
      ).then(res => {
        this.form.compileUser = res.data.data.userInfo.name;
        this.form.compileUserId = res.data.data.userInfo.id;
        this.form.reportUsername = res.data.data.userInfo.name;
        // this.reportOptions=res.data.data[openId]
        this.userOpenId = res.data.data.userInfo.openId;
        this.getReportInOrgData(res.data.data.userInfo.openId);
      });
    },
    // 填报信息
    getReportInOrgData(openId) {
      getReportInOrgData({ openIds: [openId] }).then(res => {
        this.reportInOrgObj.tableData = res.data.data[openId];
        this.reportInOrgObj.recordsTotal = res.data.data[openId].length;
        this.reportOptions = res.data.data[openId];
        this.form.reportInOrgName =
          this.form.reportInOrgName || this.reportOptions[0].name;
        this.form.reportInOrgId =
          this.form.reportInOrgId || this.reportOptions[0].orgId;
      });
      // this.getQryTree(this.form.reportInOrgId);
    },
    // 部门 start
    async getDepartData(parentId) {
      const {
        child,
        child: [{ id, abbrName, autoCode }]
      } = (
        await qryUnderOrg({
          parentId: parentId, // 全局 其他【此组件是本级及以下】
          flag: "1" // 0 公司 1 部门 2 成员
        })
      ).data.data[0];
      this.departOptions = child;
      // 默认第一个部门
      this.form.departId = id;
      this.form.departName = abbrName;
      this.form.departCode = autoCode;
    },

    // 部门选中的数据
    handleNodeClick(data) {
      this.form.departId = data.id;
      this.form.departName = data.abbrName;
      this.form.departCode = data.autoCode;
      this.$refs.selectTree.blur();
    },
    // 部门 end
    handleShowProjectNameDialog(){
      this.$refs.projectNameBakVisibleDialog.visible = true;
      this.getProjectNameData(this.projectObj.formDate);
    },
    // 获取项目名称数据
    getProjectNameData(defaultParams = this.projectObj.formDate) {
      const data = defaultParams;
      data.fillOrg = this.form.reportInOrgId;
      qryProjectDataAll(data).then(res => {
        this.projectObj.tableData = res.data.data.rows.map(n => ({
          ...n,
          projectAllName: n.zzcountryName + n.provinceName + n.zprojlocName
        }));
        this.projectObj.recordsTotal = res.data.data.recordsTotal;
      });
    },
    // 项目名称
    selectProjectName(val) {
      if (val.status === "confirm") {
        const {
          confirmSelect,
          confirmSelect: {
            zprojname,
            zproject
          }
        } = val;

        const str = this.getType(confirmSelect);

        if (str === "Object") {
          this.resetSupplierParams("projectObj");
          this.form.projectCode = zproject;
          this.form.projectName = zprojname;
        }
        this.selectProjectNameReset();
      } else {
        this[this.getSelectProjectNameStrategy[val.status]](val);
        if (["closeReset"].includes(val.status)) return; // 点击叉号只清空数据，不调接口
        this.getProjectNameData(this.projectObj.formDate);
      }
    },
    // 项目查询
    selectProjectNameSearch(val) {
      this.projectObj.formDate = val.formDate;
      this.projectObj.formDate.pageNo = 1;
    },
    // 项目名称重置
    selectProjectNameReset(val) {
      this.projectObj.formDate = {
        fillOrg: "",
        contractOrderOrg: "",
        pageNo: 1,
        pageSize: 10
      };
    },
    resetSupplierParams(str) {
      this[str].formDate = {
        ...this[str].formDate,
        pageNo: 1,
        pageSize: 10
      };
    },
    // 当前页条数
    selectProjectNamePageSize(val) {
      this.projectObj.formDate.pageSize = val.pageSize;
    },

    // 页码
    selectProjectNamePageNo(val) {
      this.projectObj.formDate.pageNo = val.pageNo;
    },
    // 核算组织 start
    handleShowAccountingOrganDialog() {
      this.$refs.accountingOrgan.visible = true;
      this.listAccountingUnitByBO();
    },
    async listAccountingUnitByBO(params = this.accountingOrganObj.formDate) {
      const { rows, recordsTotal } = (await listAccountingUnitByBO(params)).data
        .data;
      this.accountingOrganObj.tableData = rows;
      this.accountingOrganObj.recordsTotal = recordsTotal;
    },
    selectAccountingOrganName(val) {
      if (val.status === "confirm") {
        const { confirmSelect } = val;

        const str = this.getType(confirmSelect);

        if (str === "Object") {
          this.resetSupplierParams("accountingOrganObj");
          this.form.accountingOrganId = confirmSelect.acOrgId; // 核算组织id
          this.form.accountingOrgan = confirmSelect.chsName; // 核算组织名称
          this.form.accountingOrganCode = confirmSelect.acOrgCode; // 核算组织code
          this.selectProjectNameReset(null, "accountingOrganObj");
        }
      } else {
        this[this.getSelectProjectNameStrategy[val.status]](
          val,
          "accountingOrganObj"
        );
        if (["closeReset"].includes(val.status)) return; // 点击叉号只清空数据，不调接口
        this.listAccountingUnitByBO();
      }
    },
    clearAccountingOrgan() {
      this.form.accountingOrganId = ""; // 核算组织id
      this.form.accountingOrgan = ""; // 核算组织名称
      this.form.accountingOrganCode = ""; // 核算组织code
    },
    // 核算组织 end
    getType(obj) {
      return Object.prototype.toString
        .call(obj)
        .replace(/^\[object (\S+)\]$/, "$1");
    },
    // 填报单位
    changeReportInOrgId(val) {
      const tempObj = this.reportOptions.find(e => e.name === val);
      this.form.reportInOrgId = tempObj.orgId;
      this.form.reportInOrgName = tempObj.name;

      // 改变填报单位清空 数据
      // this.form.storageName = "";
      this.form.settlementCode = "";
      this.form.settlementName = "";
      this.form.supplierName = "";
      // this.form.materialForm = "";
      // this.form.warehouseName = "";
      // this.form.storageCount = "";
      // this.form.storageMoney = "";
      // this.form.invoiceCode = "";
      // this.form.invoiceName = "";
      this.form.partyBName = "";
      this.form.contractCode = "";
      this.form.contractName = "";
      this.form.categoryName = "";
      this.form.currency = "";
      this.form.settlementAmount = "";
      this.form.totalInvoiceAmount = "";
      this.form.currentInvoiceAmount = "";
      this.form.invoiceNum = "";
      this.tableData = [];
      this.$emit("updataList", this.tableData);
      this.$nextTick(() => {
        this.$refs.basicInfo.clearValidate();
      });
      this.$emit("clearTable");
    },
    formatDateTime(date) {
      let _time = new Date(date);
      var y = _time.getFullYear();
      var m = _time.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = _time.getDate();
      d = d < 10 ? "0" + d : d;
      //   var h = _time.getHours();
      //   h = h < 10 ? "0" + h : h;
      return y + "-" + m + "-" + d;
    },
    showDialog() {
      if (this.form.reportInOrgId && this.form.reportInOrgId != "") {
        this.$refs["codeNumber"].dialogTableVisibletextarea = true;
        this.$refs["codeNumber"].listConSupPage();
      } else {
        this.$showErrorMessage("请先选择填报单位");
      }
    },
    codeNumberInventoryConfirm(data) {
      this.form.settlementId = data.id;
      this.form.settlementCode = data.settlementCode;
      this.form.settlementName = data.settlementName; //结算单名称
      this.form.contractId = data.contractId;
      this.form.contractCode = data.contractCode; //合同编码
      this.form.contractName = data.contractName; //合同名称
      //   this.form.supplierName = data.supplierName; //供应商
      this.form.supplierId = data.supplierId; //供应商id
      this.form.supplierCode = data.supplierCode; //供应商编码
      this.count = data.currSetCount; //本期结算数量
      this.form.settlementCount = data.currSetCount; //本期结算数量
      this.form.storageCount = data.currSetCount;
      this.form.storageMoney = Number(data.currSetMoney).toFixed(2); //结算金额
      this.form.settlementAmount = Number(data.currSetMoney).toFixed(2);
      //   this.form.materialForm = data.materialForm; //
      //   this.form.remark = data.remarks; //留言
      this.form.compileUser = data.reportUsername; //编制人
      //   this.form.compileDate = this.formatDateTime(data.reportTime); //编制日期
      this.form.partyBName = data.supplierName; //供应商
      this.form.concId = data.contractId; //合同id
      this.form.categoryName = data.thirdCategoriesOfName; //分类名称
      this.form.currency = data.currencyName; //币种
      this.form.invoicetype = data.businessType;
      //   this.form.materialId = data.materialId, //合同清单id
      //   发票单编号
      // 发票单名称
      // 结算单名称
      //分类名称
      //币种

      if (data.id !== this.currentId) {
        //更换结算单时清空
        // this.form.settlementAmount = "";//结算金额
        // this.form.totalInvoiceAmount = "";//已收票金额
        this.form.currentInvoiceAmount = ""; //本次收票金额
        this.form.invoiceNum = ""; //发票张数
      }
      this.currentId = data.id; //储存当前id判断变化

      this.$bus.$emit("settlementCoder", this.form.settlementId);
      this.$emit("settlementCoder", this.form.settlementId);
      this.tableData = [];
      getSettlementById({
        ids: [data.id]
      }).then(res => {
        this.form.settlement = res.data.data;

        if (res.data.data.settlement.totalInvoiceAmount) {
          //已收票金额
          this.form.totalInvoiceAmount = new BigNumber(
            res.data.data.settlement.totalInvoiceAmount
          ).toFixed(2);
        } else {
          this.form.totalInvoiceAmount = "0.00";
        }
        // this.form.remark = res.data.data.settlement.remarks;
        this.$bus.$emit("businessType", res.data.data.settlement.businessType);
        this.$bus.$emit(
          "settlementBasicName",
          res.data.data.settlement.settlementName
        );
        this.$bus.$emit(
          "settlementBasicCode",
          res.data.data.settlement.settlementCode
        );
        this.$bus.$emit("settlementBasicId", res.data.data.settlement.id);
        res.data.data.settlementList.forEach(item => {
          item.count = item.settlementCount;
          if (item.isMerge == 0 || item.isMainInventory == 1) {
            item.settlementListId = item.id;
            item.storageCount = item.settlementCount;
            item.settlementMoney = item.moneyWithTax;
            this.tableData.push(item);
          }
        });
      });

      // this.$emit("updataList", this.tableData);
      this.$emit("clearTable");
    },
    handleTrim(str) {
      this.form[str] = this.form[str].trim();
      // this.form[str] = this.form[str].replace(/(^\s*)|(\s*)$/g, "");
    }
  },
  mounted() {
    this.form.compileDate = new Date();
    let basicGetDate = this.form.compileDate; //获取时间
    this.$emit("basicGetDate", basicGetDate);
  }
};
</script>

<style scoped lang="scss">
// /deep/ .el-input {
//   width: 260px;
// }

/deep/ .el-button--single-number {
  width: 46px;
  margin-left: 10px;
  padding: 0 9px;
}

/deep/ .ccui-pre-form-item {
  .el-form-item__label {
    line-height: 16px;
  }
}

.remarkClass {
  width: calc(50% + 340px);
}

// 基本信息样式
.relative {
  position: relative;
  .chereay {
    margin-left: 10px;
    position: absolute;
    top: 0;
    right: -80px;
  }
}
.demo-ruleForm {
  width: 80%;
  margin: 20px 0 0 50px;
}
.demo-ruleForm {
  margin: 20px 0 70px 50px;
  &::v-deep {
    .el-input input {
      padding-right: 50px;
    }
  }
}
</style>
